package com.jinbai.dao;

import com.jinbai.model.User;
import com.jinbai.util.DBUtil;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDao {
    @SneakyThrows
    public void registerNewUser(String username, String password, String avatar, String gitRepo) {
        try (Connection con = DBUtil.connection()) {
            String sql = "insert into blog.users (username, password, avatar, gitRepo) values (?, ?, ?, ?)";
            try (PreparedStatement ps = con.prepareStatement(sql)) {
                ps.setString(1, username);
                ps.setString(2, password);
                ps.setString(3, avatar);
                ps.setString(4, gitRepo);
                ps.executeUpdate();
            }
        }
    }

    @SneakyThrows
    public User getUserByUsernameAndPassword(String username, String password) {
        try (Connection con = DBUtil.connection()) {
            String sql = "select uid, avatar, gitRepo from blog.users where username = ? and password = ?";
            try (PreparedStatement ps = con.prepareStatement(sql)) {
                ps.setString(1, username);
                ps.setString(2, password);
                ResultSet rs = ps.executeQuery();
                if (!rs.next()) {
                    return null;
                }
                return new User(rs.getInt("uid"), username, password, rs.getString("avatar"), rs.getString("gitRepo"));
            }
        }
    }
}
